package geeks.dao;

import geeks.excepcion.DAOExcepcion;
import geeks.modelo.Rol;
import geeks.util.ConexionBD;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

public class RolDAO extends BaseDao{
	
	public Rol buscar(int idRol) throws DAOExcepcion {
		String query = "SELECT idRol, descRol FROM Rol WHERE idRol = ?;";
		
		Rol objRol = null;
		
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			
			stmt.setInt(1, idRol);
			
			rs = stmt.executeQuery();
			
			if(rs.next()){
				objRol = new Rol();
				
				objRol.setIdRol(rs.getInt("idRol"));
				objRol.setDescRol(rs.getString("descRol"));
			}
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
	
		return objRol;
	}
	
	public Collection<Rol> listar() throws DAOExcepcion {
		String query = "SELECT idRol, descRol FROM Rol;";
		
		Collection<Rol> lista = new ArrayList<Rol>();
				
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			
			rs = stmt.executeQuery();
			
			while(rs.next()){
				Rol objRol = new Rol();			
				
				objRol.setIdRol(rs.getInt("idRol"));
				objRol.setDescRol(rs.getString("descRol"));
				
				lista.add(objRol);
			}
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
	
		return lista;
	}
	
}
